//https://leetcode.cn/problems/maximum-sum-circular-subarray/

class Solution {
public:
    int maxSubarraySumCircular(vector<int>& nums) {
        int n = nums.size();
        int sum = 0;
        for (auto e : nums)
        {
            sum += e;
        }

        int maxret = maxarray(n, nums);
        int minret = minarray(n, nums);

        if (sum == minret) return maxret;

        return max(maxret, sum - minret);
    }

    int maxarray(int n, vector<int>& nums)
    {
        vector<int> dp(n + 1);
        int ret = INT_MIN;
        for (int i = 1; i <= n; i++)
        {
            dp[i] = max(nums[i - 1], dp[i - 1] + nums[i - 1]);
            ret = max(ret, dp[i]);
        }

        return ret;

    }

    int minarray(int n, vector<int>& nums)
    {
        vector<int> dp(n + 1);
        int ret = INT_MAX;
        for (int i = 1; i <= n; i++)
        {
            dp[i] = min(nums[i - 1], dp[i - 1] + nums[i - 1]);
            ret = min(ret, dp[i]);
        }

        return ret;

    }
};